# coding: utf-8
import urllib.parse
from django.conf import settings
from .huaweicloudcenter import novalEcsHost

from django.http.response import HttpResponse, JsonResponse
from .huaweicloudcenter import huaweiregion
from django.views import View
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.http.http_config import HttpConfig
from huaweicloudsdkecs.v2 import *
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkevs.v2 import *
from huaweicloudsdkevs.v2.region.evs_region import EvsRegion


class novaListCounts(View):

    @staticmethod
    def post(request):
        ak = settings.AK
        sk = settings.SK
        list = []
        total = 0
        for key in huaweiregion:
            credentials = BasicCredentials(ak, sk)
            # esc主机信息接口
            client = EcsClient.new_builder().with_credentials(
                credentials).with_region(EcsRegion.value_of(key)).build()

            try:
                request = ListServersDetailsRequest()
                response = eval(str(client.list_servers_details(request)))
                # print(response)
                # 获取接口参数ecs主机
                ecscount = response["count"]
                list.append(ecscount)

            except exceptions.ClientRequestException as e:
                print(e.status_code)
                print(e.request_id)
                print(e.error_code)
                print(e.error_msg)
        # 计算所有区域中ecs主机数量
        for ele in range(len(list)):

            total = total + list[ele]
        return JsonResponse(total, safe=False)


class novaListServers(View):
    @staticmethod
    def post(request):
        data = (str(urllib.parse.unquote(request.body)))

        parseList = []
        volumeVolues = []
        bb = []
        volumesId = []
        ecsId = []
        for k, v in huaweiregion.items():
            if v == data:
                recomList = []
                credentials = BasicCredentials(ak, sk)
                # 获取ecs主机信息
                client = EcsClient.new_builder().with_credentials(
                    credentials).with_region(EcsRegion.value_of(k)).build()
                try:
                    request = ListServersDetailsRequest()
                    # 设置查询的限制和分页，默认limit = 25 offset 无上限
                    request.limit = 100
                    request.offset = 1
                    response = eval(str(client.list_servers_details(request)))
                    # 获取所有参数
                    # print(response)
                    # 获取接口参数中服务器信息
                    ecsservers = response["servers"]
                    recomList.append(ecsservers)

                    # print("ecs__________", ecsservers)

                except exceptions.ClientRequestException as e:
                    print(e.status_code)
                    print(e.request_id)
                    print(e.error_code)
                    print(e.error_msg)

                # ecs 磁盘信息接口

                clientDisk = EvsClient.new_builder().with_credentials(
                    credentials).with_region(EvsRegion.value_of(k)).build()

                # ecs 磁盘信息接口参数
                try:
                    request = ListVolumesRequest()
                    response = eval(str(clientDisk.list_volumes(request)))
                    volumesList = response["volumes"]
                    recomList.append(volumesList)

                    # print("disk____________", response)

                except exceptions.ClientRequestException as e:
                    print(e.status_code)
                    print(e.request_id)
                    print(e.error_code)
                    print(e.error_msg)
                for k in recomList:
                    for i in k:
                        print(i)
                        print("i____________", i["addresses"])
                        # 获取主机名
                        # for y in i:
                        #     print("y______", y)
                        # addr = []
                        # for v in y["addresses"]:
                        #    # 获取主机的IP地址私有地址和公有地址
                        #     values = k["addresses"][v]
                        #     for v in values:
                        #         addr.append(v["addr"])
                        # 转换类型 list => str
                        #  addr = ' \n'.join(addr)
                        #  # 获取esc主机id
                        #   ecsId.append(k["id"])
                        #  # 获取磁盘id
                        #    for v in k["os_extended_volumesvolumes_attached"]:
                        #         volumesId.append(v["id"])
                        #         tmpValue = {"name": k["name"], "addresses": addr,
                        #                     "host_status": k["host_status"], "created": k["created"], "ram": k["flavor"]["ram"], "vcpus": k["flavor"]["vcpus"], "image_name": k["metadata"]["image_name"], "os_bit": k["metadata"]["os_bit"], "os_type": k["metadata"]["os_type"]}
                        #         bb.append(tmpValue)
                        #     print("i_name___________", i["name"])
                        #     print("i____________", i)

        #         # print(ecsservers)
        #         # 重组数据
        #         for volumeVolue in volumeVolues:
        #             os_size = {"os_size": volumeVolue["size"]}
        #             newVoluems = volumeVolue["attachments"]
        #             for voluem in newVoluems:
        #                 os_size.update(voluem)
        #             recomList.append(os_size)
        #         # 获取主机名
        #         for k in parseList:
        #             addr = []
        #             for v in k["addresses"]:
        #               # 获取主机的IP地址私有地址和公有地址
        #                 values = k["addresses"][v]
        #                 for v in values:
        #                     addr.append(v["addr"])
        #             # 转换类型 list => str
        #             addr = ' \n'.join(addr)
        #             # 获取esc主机id
        #             ecsId.append(k["id"])
        #             # 获取磁盘id
        #             for v in k["os_extended_volumesvolumes_attached"]:
        #                 volumesId.append(v["id"])

        #             tmpValue = {"name": k["name"], "addresses": addr,
        #                         "host_status": k["host_status"], "created": k["created"], "ram": k["flavor"]["ram"], "vcpus": k["flavor"]["vcpus"], "image_name": k["metadata"]["image_name"], "os_bit": k["metadata"]["os_bit"], "os_type": k["metadata"]["os_type"]}

        #             recomList.append(tmpValue)

        # print("recomList________", recomList)
        return JsonResponse(bb, safe=False)


class novaListVolumes(View):
    @staticmethod
    def post(request):
        data = (str(urllib.parse.unquote(request.body)))
        novalEcsHost.getEcs("华东-上海二")
        # print(novalEcsHost.getEcs)
        return HttpResponse("okkk")
